package jack.newbee.mall.controller.jdbctemplate;



import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@RestController
public class JdbcController {

    private final JdbcTemplate jdbcTemplate;

    public JdbcController(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //create
    @GetMapping("/jdbctemplate/insert")
    public String insert(String type, String name) {
        if(StringUtils.isEmpty(type) || StringUtils.isEmpty(name)) {
            return "参数异常";
        }

        String sql = "insert into jdbc_test(`ds_type`, `ds_name`) " +
                "value (\"" + type + "\", \"" + name + "\")";
        System.out.println(sql);
        jdbcTemplate.execute(sql);
        return "sql执行完毕";
    }

    //delete
    @GetMapping("/jdbctemplate/delete")
    public String delete(int id) {
        if(id < 0) {
            return "参数异常";
        }


        String sql = "select * from jdbc_test where ds_id=\"" + id + "\"";
        System.out.println(sql);
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
        if(CollectionUtils.isEmpty(result)) {
            System.out.println("不存在该参数 删除失败");
        }

        sql = "delete from jdbc_test where ds_id=\"" + id + "\"";
        System.out.println(sql);
        jdbcTemplate.execute(sql);
        return "sql执行完毕";
    }

    //update
    @GetMapping("/jdbctemplate/update")
    public String update(int id, String type, String name) {
        if(id < 0|| StringUtils.isEmpty(type) || StringUtils.isEmpty(name)) {
            return "参数异常 ";
        }

        String sql = "select * from jdbc_test where ds_id=\"" + id + "\"";
        System.out.println(sql);
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
        if(CollectionUtils.isEmpty(result)) {
            System.out.println("不存在该参数 无法修改");
        }

        sql = "update jdbc_test set `ds_type`=\"" + type + "\", `ds_name` = \"" + name+ "\" ";
        System.out.println(sql);
        jdbcTemplate.execute(sql);
        return "sql执行完毕";
    }
}
